package grpc

import (
	"context"
	"jihe.common/protos/user_server/proto"
	"user_server/internal/models/c_user"
	"user_server/internal/models/user"
)

func (s *Server) UserGetCUsersByIds(c context.Context, in *proto.UserGetCUsersByIdsReq) (ret *proto.UserCUsers, err error) {
	ret = new(proto.UserCUsers)
	cUserTbl := c_user.NewModel(s.Pgsql.Get())
	ret.List, err = cUserTbl.GetByIds(in)
	return
}

func (s *Server) UserCUserCreate(c context.Context, in *proto.UserCUser) (out *proto.UserCUser, err error) {
	out = new(proto.UserCUser)
	db := s.Pgsql.Get()
	tx, err := db.Begin()
	if err != nil {
		return
	}
	cUserTbl := c_user.NewTx(tx)
	cUserInfo, err := cUserTbl.Create(in)
	if err != nil {
		_ = tx.Rollback()
		return
	}
	err = user.NewTx(tx).Create(&proto.UserUser{
		Uid:      cUserInfo.Id,
		Role:     2,
		Discount: 100,
	})
	if err != nil {
		_ = tx.Rollback()
		return
	}
	err = tx.Commit()
	if err != nil {
		return
	}
	out = cUserInfo
	return
}

func (s *Server) UserCUserUpdate(c context.Context, in *proto.UserCUser) (out *proto.UserCUser, err error) {
	cUserTbl := c_user.NewModel(s.Pgsql.Get())
	err = cUserTbl.UpdateByPhone(in)
	if err != nil {
		return
	}
	return cUserTbl.GetByPhone(in.Phone)
}
